package com.dailyblue.java.spring.jwt.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.jwt.config.JwtConfig;
import com.dailyblue.java.spring.jwt.util.ResultCode;
import com.dailyblue.java.spring.jwt.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始校验用户是否登录");

        // 1. 获取到用户的headers,判断这个token是否合法
        boolean b = JwtConfig.checkToken(request);
        log.info("b:{}", b);
        if (!b) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONArray.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN)));
            return false;
        }
        // 2. 和redis中的进行比对
        String id = JwtConfig.getMemberIdByJwtToken(request);
        log.info("id:{}", id);
        HashOperations hash = stringRedisTemplate.opsForHash();
        Object obj = hash.get("token", id);
        log.info("obj:{}", obj);
        if (obj == null) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSONArray.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN)));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
